/**
 * Copyright (c) 2015-2016, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.platform.common.secret.utils;

import cn.hutool.core.convert.Convert;
import com.platform.common.core.utils.StringUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author liangyinan2001
 * @date 2019/10/15 14:12
 * @Description 高频方法集合类
 */
public class ToolUtil {

    /**
     * 获取随机位数的字符串
     *
     * @author liangyinan2001
     * @Date 2017/8/24 14:09
     */
    public static String getRandomString(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 生成一个随机的密码
     *
     * @author liangyinan2001
     * @Date 2019/8/1 14:09
     */
    public static String getRandomPassword() {
        String base0 = "abcdefghijklmnopqrstuvwxyz";
        String base1 = "0123456789";
        String base2 = "._~!@#$^&*";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            int number = random.nextInt(base0.length());
            sb.append(base0.charAt(number));
        }
        for (int i = 0; i < 3; i++) {
            int number = random.nextInt(base1.length());
            sb.append(base1.charAt(number));
        }
        sb.append(base2.charAt(random.nextInt(base2.length())));
        return sb.toString();
    }

    /**
     * 生成一个随机的SM4密钥
     *
     * @author liangyinan2001
     * @Date 2019/8/1 14:09
     */
    public static String getRandomSm4Key() {
        String base0 = "abcdefghijklmnopqrstuvwxyz";
        String base1 = "0123456789";
        String base2 = "._~!@#$^&*";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 9; i++) {
            int number = random.nextInt(base0.length());
            sb.append(base0.charAt(number));
        }
        for (int i = 0; i < 5; i++) {
            int number = random.nextInt(base1.length());
            sb.append(base1.charAt(number));
        }
        for (int i = 0; i < 2; i++) {
            int number = random.nextInt(base2.length());
            sb.append(base2.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 获取异常的具体信息
     *
     * @author liangyinan2001
     * @Date 2017/3/30 9:21
     * @version 2.0
     */
    public static String getExceptionMsg(Exception e) {
        StringWriter sw = new StringWriter();
        try {
            e.printStackTrace(new PrintWriter(sw));
        } finally {
            try {
                sw.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return sw.getBuffer().toString().replaceAll("\\$", "T");
    }

    /**
     * 比较两个对象是否相等。<br>
     * 相同的条件有两个，满足其一即可：<br>
     * 1. obj1 == null && obj2 == null; 2. obj1.equals(obj2)
     *
     * @param obj1 对象1
     * @param obj2 对象2
     * @return 是否相等
     */
    public static boolean equals(Object obj1, Object obj2) {
        return (obj1 != null) ? (obj1.equals(obj2)) : (obj2 == null);
    }

    /**
     * 比较两个字符串是否相等，不区分大小写。<br>
     *
     * @param str1 字符串1
     * @param str2 字符串2
     * @return 是否相等
     */
    public static boolean equalsIgnoreCase(String str1, String str2) {
        return (str1 != null) ? (str1.equalsIgnoreCase(str2)) : (str2 == null);
    }

    /**
     * 计算对象长度，如果是字符串调用其length函数，集合类调用其size函数，数组调用其length属性，其他可遍历对象遍历计算长度
     *
     * @param obj 被计算长度的对象
     * @return 长度
     */
    public static int length(Object obj) {
        if (obj == null) {
            return 0;
        }
        if (obj instanceof CharSequence) {
            return ((CharSequence) obj).length();
        }
        if (obj instanceof Collection) {
            return ((Collection<?>) obj).size();
        }
        if (obj instanceof Map) {
            return ((Map<?, ?>) obj).size();
        }

        int count;
        if (obj instanceof Iterator) {
            Iterator<?> iter = (Iterator<?>) obj;
            count = 0;
            while (iter.hasNext()) {
                count++;
                iter.next();
            }
            return count;
        }
        if (obj instanceof Enumeration) {
            Enumeration<?> enumeration = (Enumeration<?>) obj;
            count = 0;
            while (enumeration.hasMoreElements()) {
                count++;
                enumeration.nextElement();
            }
            return count;
        }
        if (obj.getClass().isArray() == true) {
            return Array.getLength(obj);
        }
        return -1;
    }

    /**
     * 对象中是否包含元素
     *
     * @param obj     对象
     * @param element 元素
     * @return 是否包含
     */
    public static boolean contains(Object obj, Object element) {
        if (obj == null) {
            return false;
        }
        if (obj instanceof String) {
            if (element == null) {
                return false;
            }
            return ((String) obj).contains(element.toString());
        }
        if (obj instanceof Collection) {
            return ((Collection<?>) obj).contains(element);
        }
        if (obj instanceof Map) {
            return ((Map<?, ?>) obj).values().contains(element);
        }

        if (obj instanceof Iterator) {
            Iterator<?> iter = (Iterator<?>) obj;
            while (iter.hasNext()) {
                Object o = iter.next();
                if (equals(o, element)) {
                    return true;
                }
            }
            return false;
        }
        if (obj instanceof Enumeration) {
            Enumeration<?> enumeration = (Enumeration<?>) obj;
            while (enumeration.hasMoreElements()) {
                Object o = enumeration.nextElement();
                if (equals(o, element)) {
                    return true;
                }
            }
            return false;
        }
        if (obj.getClass().isArray() == true) {
            int len = Array.getLength(obj);
            for (int i = 0; i < len; i++) {
                Object o = Array.get(obj, i);
                if (equals(o, element)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 对象是否不为空(新增)
     *
     * @param obj String,List,Map,Object[],int[],long[]
     * @return
     */
    public static boolean isNotEmpty(Object obj) {
        return !isEmpty(obj);
    }

    /**
     * 对象是否为空
     *
     * @param obj String,List,Map,Object[],int[],long[]
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static boolean isEmpty(Object obj) {
        if (obj == null) {
            return true;
        }
        if (obj instanceof String) {
            if (StringUtils.isBlank(obj.toString().trim())) {
                return true;
            }
        } else if (obj instanceof List) {
            if (((List) obj).size() == 0) {
                return true;
            }
        } else if (obj instanceof Map) {
            if (((Map) obj).size() == 0) {
                return true;
            }
        } else if (obj instanceof Set) {
            if (((Set) obj).size() == 0) {
                return true;
            }
        } else if (obj instanceof Object[]) {
            if (((Object[]) obj).length == 0) {
                return true;
            }
        } else if (obj instanceof int[]) {
            if (((int[]) obj).length == 0) {
                return true;
            }
        } else if (obj instanceof long[]) {
            if (((long[]) obj).length == 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * 对象组中是否存在 Empty Object
     *
     * @param os 对象组
     * @return
     */
    public static boolean isOneEmpty(Object... os) {
        for (Object o : os) {
            if (isEmpty(o)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 对象组中是否全是 Empty Object
     *
     * @param os
     * @return
     */
    public static boolean isAllEmpty(Object... os) {
        for (Object o : os) {
            if (!isEmpty(o)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 是否为数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str.replace(".", "")).matches();
    }

    /**
     * String是否为BigDecimal
     *
     * @param valueStr
     * @return
     */
    public static boolean isBigDecimal(String valueStr) {
        try {
            new BigDecimal(valueStr);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 如果为空, 则调用默认值
     *
     * @param str
     * @return
     */
    public static Object getValue(Object str, Object defaultValue) {
        if (isEmpty(str)) {
            return defaultValue;
        }
        return str;
    }

    /**
     * 字符串如果为空, 则调用默认值
     *
     * @param str
     * @return
     */
    public static String getStringValue(String str, String defaultValue) {
        if (isEmpty(str)) {
            return defaultValue;
        }
        return str;
    }



    /**
     * 强转->string,并去掉多余空格
     *
     * @param str
     * @return
     */
    public static String toStr(Object str) {
        return toStr(str, "");
    }

    /**
     * 强转->string,并去掉多余空格
     *
     * @param str
     * @param defaultValue
     * @return
     */
    public static String toStr(Object str, String defaultValue) {
        if (null == str) {
            return defaultValue;
        }
        return str.toString().trim();
    }

    /**
     * map的key转为小写
     *
     * @param map
     * @return Map<String, Object>
     */
    public static Map<String, Object> caseInsensitiveMap(Map<String, Object> map) {
        Map<String, Object> tempMap = new HashMap<>(16);
        for (String key : map.keySet()) {
            tempMap.put(key.toLowerCase(), map.get(key));
        }
        return tempMap;
    }

    /**
     * 获取map中第一个数据值
     *
     * @param <K> Key的类型
     * @param <V> Value的类型
     * @param map 数据源
     * @return 返回的值
     */
    public static <K, V> V getFirstOrNull(Map<K, V> map) {
        V obj = null;
        for (Entry<K, V> entry : map.entrySet()) {
            obj = entry.getValue();
            if (obj != null) {
                break;
            }
        }
        return obj;
    }

    /**
     * 创建StringBuilder对象
     *
     * @return StringBuilder对象
     */
    public static StringBuilder builder(String... strs) {
        final StringBuilder sb = new StringBuilder();
        for (String str : strs) {
            sb.append(str);
        }
        return sb;
    }

    /**
     * 创建StringBuilder对象
     *
     * @return StringBuilder对象
     */
    public static void builder(StringBuilder sb, String... strs) {
        for (String str : strs) {
            sb.append(str);
        }
    }

    /**
     * 去掉指定后缀
     *
     * @param str    字符串
     * @param suffix 后缀
     * @return 切掉后的字符串，若后缀不是 suffix， 返回原字符串
     */
    public static String removeSuffix(String str, String suffix) {
        if (isEmpty(str) || isEmpty(suffix)) {
            return str;
        }

        if (str.endsWith(suffix)) {
            return str.substring(0, str.length() - suffix.length());
        }
        return str;
    }

    /**
     * 判断是否是windows操作系统
     *
     * @author stylefeng
     * @Date 2017/5/24 22:34
     */
    public static Boolean isWinOs() {
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取临时目录
     *
     * @author stylefeng
     * @Date 2017/5/24 22:35
     */
    public static String getTempPath() {
        return System.getProperty("java.io.tmpdir");
    }

    /**
     * 把一个数转化为int
     *
     * @author liangyinan2001
     * @Date 2017/11/15 下午11:10
     */
    public static Integer toInt(Object val) {
        if (val instanceof Double) {
            BigDecimal bigDecimal = new BigDecimal((Double) val);
            return bigDecimal.intValue();
        } else {
            return Integer.valueOf(val.toString());
        }

    }

    /**
     * 获取项目路径
     */
    public static String getWebRootPath(String filePath) {
        try {
            String path = ToolUtil.class.getClassLoader().getResource("").toURI().getPath();
            path = path.replace("/WEB-INF/classes/", "");
            path = path.replaceAll("/target/.*", "");
            path = path.replace("file:/", "");
            if (ToolUtil.isEmpty(filePath)) {
                return path;
            } else {
                return path + "/" + filePath;
            }
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 补号
     *
     * @param prefix
     * @param bits
     * @param maxNum
     * @return
     */
    public static String pad(String prefix, int bits, Integer maxNum) {
        StringBuffer append = new StringBuffer();
        int i = Convert.toStr(maxNum).length();
        while (i < bits) {
            append.append('0');
            i++;
        }
        append.append(maxNum);
        return prefix + append.toString();
    }

    /**
     * 判断是否为金额字符串
     *
     * @param str
     * @return
     */
    public static boolean isAmountOfMoney(String str) {
        // 判断小数点后2位的数字的正则表达式
        Pattern pattern = Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$");
        Matcher match = pattern.matcher(str);
        if (match.matches() == false) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 手机号屏蔽
     *
     * @param phone
     * @return
     */
    public static String getPhoneEnc(String phone) {
        String res = "";
        if (ToolUtil.isNotEmpty(phone)) {
            phone = phone.trim();
            if (phone.length() > 3) {
                res = phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4);
            }
        }
        return res;
    }


    /**
     * 根据手机号生成登录账号,手机号中间4位替换为随机小写字母
     *
     * @param mobileNo
     * @return
     */
    public static String generateAccountByMobileNo(String mobileNo) {
        String res = "";
        if (ToolUtil.isNotEmpty(mobileNo)) {
            mobileNo = mobileNo.trim();
            if (mobileNo.length() > 7) {
                StringBuilder sb = new StringBuilder();
                int j = 1;
                while (j++ < 5) {
                    int rand = (int) (Math.random() * 26 + 97);
                    sb.append((char) rand);
                }
                res = mobileNo.substring(0, 3) + sb + mobileNo.substring(mobileNo.length() - 4);
            }
        }
        return res;
    }


    /**
     * 身份证加密
     *
     * @param idNo
     * @return
     */
    public static String getIdEnc(String idNo) {
        String res = "";
        if (ToolUtil.isNotEmpty(idNo)) {
            idNo = idNo.trim();
            if (idNo.length() >= 18) {
                res = idNo.substring(0, 3) + "***********" + idNo.substring(14, 18);
            } else {
                res = "******************";
            }
        }
        return res;
    }

    /**
     * 邮箱地址脱敏
     *
     * @param email
     * @return
     */
    public static String getEmailEnc(String email) {
        String res = "";
        if (ToolUtil.isNotEmpty(email)) {
            email = email.trim();
            if (email.length() >= 3) {
                int index = email.indexOf("@");
                if (index >= 0) {
                    if (index >= 3) {
                        res = email.substring(0, 3) + "****" + email.substring(index);
                    } else {
                        res = email.substring(0, index) + "****" + email.substring(index);
                    }
                }
            }
        }
        return res;
    }


}
